﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Rose.Models;
using Rose.Helper;
using System.Web.Security;

namespace Rose.Helper
{
    public class LoverRelationHelpModel
    {
        private   Database_RoseEntities db = new Database_RoseEntities();

        #region Roles

        private  bool UpdateLoverRole(string selfId, string loverId,bool isAdd)
        {

            try
            {
                if (isAdd)
                {
                    if (!Roles.IsUserInRole(selfId, "Lover"))
                        Roles.AddUserToRole(selfId, "Lover");

                    if (!Roles.IsUserInRole(loverId, "Lover"))
                        Roles.AddUserToRole(loverId, "Lover");
                }
                else
                {
                    if (Roles.IsUserInRole(selfId, "Lover"))
                        Roles.RemoveUserFromRole(selfId, "Lover");
                    if (Roles.IsUserInRole(loverId, "Lover"))
                        Roles.RemoveUserFromRole(loverId, "Lover");

                }
                return true;
            }
            catch { return false; }
        }

        


        #endregion

        #region AddLoverToRelation  RemoveLoverFromRelation  UpdateUserInfo all-private

        private   bool AddLoverToRelation(string selfId, string loverId)
        {
          
            
                try
                {
                    if (!IsSelfLoverExist(selfId))
                    {
                        UserInfo selfInfo = db.UserInfos.Where(c => c.Id == selfId).First();
                        selfInfo.HasLover = true;
                        selfInfo.LoverId = loverId;
                        selfInfo.Score += int.Parse(Rose.ViewRes.Defaultresx.LoverAddScore);
                        db.SaveChanges();
                        return true;

                    }
                    return true;

                }
                catch { return false; }
          
           

        }

        private  bool RemoveLoverFromRelation(string selfId, string loverId)
        {
            try
            {
                UserInfo selfInfo = db.UserInfos.Where(c => c.Id == selfId).First();
                selfInfo.HasLover = false;
                selfInfo.LoverId = loverId;
              
                db.SaveChanges();
                return true;
            }
            catch { return false; }
        }

        private  bool UpdateUserInfo(string selfId, string loverId,bool isAdd)
        {
            
            if (isAdd)
                return UpdateLoverRole(selfId, loverId, isAdd)&& AddLoverToRelation(selfId, loverId) && AddLoverToRelation(loverId, selfId);
            else
                return UpdateLoverRole(selfId, loverId, isAdd)&& RemoveLoverFromRelation(selfId, loverId) && RemoveLoverFromRelation(loverId, selfId);
        }

        

        #endregion 

        #region CreateLoverRelation private

        private  bool CreateLoverRelation(string manId, string womanId, bool open, bool manCreate)
        {
            try
            {

                if (!IsSelfLoverExist(manId)&&!IsSelfLoverExist(womanId))
                {
                    LoverRelation loverRelatioin = new LoverRelation()
                      {
                          Id = Guid.NewGuid(),
                          CreateTime = DateTime.Now,
                          CancelTime = DateTime.MaxValue,
                          IsCancel = false,
                          IsOpen = open,
                          IsManCancel = false,
                          IsManCreate = manCreate,
                          ManId = manId,
                          WomanId = womanId
                      };
                    db.AddToLoverRelations(loverRelatioin);
                    db.SaveChanges();
                }
                return true;
            }
            catch
            { return false; }
        }
        #endregion

        #region helpcheck isExist
        public  bool IsSelfAlreadyRequest(string selfId)
        {

            var returnModel = db.RequestLovers.Where(c => c.UserId == selfId);

            return returnModel.Count() > 0 ? true : false;
        }

        public  bool IsRequestBeCleard(string requestId)
        {
            return db.RequestLovers.Where(c => c.Id == new Guid(requestId)).Count() <= 0;
        }


        public  bool IsSelfLoverExist(string selfId)
        {
            return new  CheckHelpModel().CheckUserInfo(selfId).HasLover;
        }

        public  bool IsGenderDifferent(string loverId, string selfId)
        { 
            return  (new CheckHelpModel().CheckUserInfo(selfId).IsMan )!=( new CheckHelpModel().CheckUserInfo(loverId).IsMan);
        }

        #endregion

        #region RequestToLover
        public  string  RequestToLover(string selfId)
        {
            try
            {
                if (IsSelfAlreadyRequest(selfId))
                    return string.Empty;
                if (IsSelfLoverExist(selfId))
                    return string.Empty;
                RequestLover requestLover = new RequestLover()
                {
                    CreateTime = DateTime.Now,
                    Id = Guid.NewGuid(),
                    UserId = selfId,
                    TargetId = string.Empty,
                    IsAccepted = false,
                    IsResponsed = false
                };
                db.AddToRequestLovers(requestLover);
                db.SaveChanges();
                return requestLover.Id.ToString();
            }
            catch
            { return string.Empty; }
        }
        #endregion
        //when the request is sent,we don't know the gender is different

        #region  RejectRequest

        public  bool RejectRequest(string requestId, string selfId)
        {
            try
            {
                Guid guidId = new Guid(requestId);
                RequestLover requestLover = db.RequestLovers.Where(c => c.Id == guidId).FirstOrDefault();
                if (requestLover == null)
                    return false;
                ///because the request is not exist,so return false,if the user want to cancel this request,he must user another function;
                requestLover.IsAccepted = false;
                requestLover.IsResponsed = true;
                db.SaveChanges();
                DeleteRequestLover(requestId);
                return true;
            }
            catch { return false; }
        }

        #endregion



        #region  AcceptRequestAndUpdateDatabase  AcceptRequestNotUpdateDatabase

        private  bool AcceptRequestNotUpdateDatabase(string requestId, string selfId)
        {
            try
            {
                Guid guidId = new Guid(requestId);
                RequestLover requestLover = db.RequestLovers.Where(c => c.Id == guidId).FirstOrDefault();
                if (requestLover == null)
                    throw new ArgumentNullException();
                requestLover.IsAccepted = true;
                requestLover.IsResponsed = true;
                db.SaveChanges();
                DeleteRequestLover(requestId);
                return true;
            }
            catch { return false; }
        }

        public  bool AcceptRequestAndUpdateDatabase(string requestId, string selfId,bool open)
        {
            try
            {
                UserInfo selfInfo =new CheckHelpModel().CheckUserInfo(selfId);
                bool selfIsMan = selfInfo.IsMan ? true : false;

                RequestLover requestLover =new CheckHelpModel().CheckRequestLover(requestId);
                string loverId = requestLover.UserId;

                

                string manId=selfIsMan?selfId:loverId;
                string womanId=selfIsMan?loverId:selfId;
                bool manCreate=selfIsMan? false:true;

                return AcceptRequestNotUpdateDatabase(requestId, selfId)
                        &&
                      CreateLoverRelation(manId, womanId, open, manCreate)
                        &&
                     UpdateUserInfo(selfId, loverId,true);

               
            }
            catch
            { return false; }
        }
        #endregion

        #region DeleteRequestLover

        

        private  bool DeleteRequestLover(Guid guidId)
        {
            try
            {
                
                RequestLover requestLover = db.RequestLovers.Where(c => c.Id == guidId).FirstOrDefault();
                if (requestLover == null)
                    return true;//没有的话就表示删除了
                db.RequestLovers.DeleteObject(requestLover);
                db.SaveChanges();
                return true;
            }
            catch { return false; }
        }
        private  bool DeleteRequestLover(string requestId)
        {
            return  DeleteRequestLover(new Guid(requestId));
        }

        private  bool DeleteRequestLover(RequestLover requestLover)
        {
            try
            {
                if (requestLover == null)
                    return true;
                db.RequestLovers.DeleteObject(requestLover);
                db.SaveChanges();
                return true;
            }
            catch
            { return false; }
        }

        public  void DeleteOutTimeRequestLover(TimeSpan timeSpan)
        {
            foreach (RequestLover requestLover in db.RequestLovers)
            {
                try
                {
                    if (DateTime.Now - requestLover.CreateTime > timeSpan)
                        DeleteRequestLover(requestLover);
                    //each step savechange;
                }
                catch
                {
                    continue;
                }
            }

        }
        #endregion

        #region  GetRequestLover

        public  RequestModel GetRequestLover(string requestId)
        {
            RequestLover requestLover =new CheckHelpModel().CheckRequestLover(requestId);
            UserInfo requestInfo =new CheckHelpModel().CheckUserInfo(requestLover.UserId);
            RequestModel returnModel = new RequestModel()
            {


                RequestId = requestId,
                RequestName = requestInfo.Name,
                Gender = requestInfo.Gender,
                Address = requestInfo.Address,
                ImagePath = requestInfo.ImagePath,
                SchoolYear = requestInfo.SchoolYear.ToString(),
                UserId = requestInfo.Id,
                MajorClass = requestInfo.CollegeMajorClass,
               University=requestInfo.University,
                Hobbies = new UserInfoHelpModel().GetHobbies(requestInfo.Id)

            };
            return returnModel;
        }

        #endregion

        #region DeleteLoverRelation
        public  void DeleteLoverRelation(string selfId)
        {
            if (IsSelfLoverExist(selfId))
            {
                UserInfo selfInfo =new CheckHelpModel().CheckUserInfo(selfId);
                bool isMan = selfInfo.IsMan;
                LoverRelation loverRelation = new LoverRelation();
                string loverId = string.Empty;
                if (isMan)
                {
                    loverRelation = db.LoverRelations.Where(c => c.ManId == selfId).FirstOrDefault();
                    loverId = loverRelation.WomanId;
                }
                else
                {
                    loverRelation = db.LoverRelations.Where(c => c.WomanId == selfId).FirstOrDefault();
                    loverId = loverRelation.ManId;
                }

                if (UpdateUserInfo(selfId, loverId, false))
                {

                    loverRelation.CancelTime = DateTime.Now;
                    loverRelation.IsCancel = true;
                    loverRelation.IsManCancel = isMan;
                    db.SaveChanges();
                    ///not delete the mark in the datebase,because this maybe userful for us;
                }
            }
        }
        

        #endregion

      

        

    }
}



  